<template>
  <div>
    <el-form :model="newBook" label-width="100px" style="margin-bottom: 20px;" @submit.native.prevent="addBook">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="title">
            <el-input v-model="newBook.title"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="author">
            <el-input v-model="newBook.author"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="copies">
            <el-input v-model.number="newBook.copies"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" native-type="submit" style="margin-top: 5px;">添加图书</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 图书表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="title" label="Title" width="180"></el-table-column>
      <el-table-column prop="author" label="Author" width="180"></el-table-column>
      <el-table-column prop="copies" label="Copies"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="deleteBook(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newBook: {
        title: '',
        author: '',
        copies: 0
      },
      tableData: [
        { id: '1', title: 'Python编程', author: 'John Doe', copies: '4' },
        { id: '2', title: '历史的秘密', author: 'Jane Smith', copies: '3' },
        { id: '3', title: '宇宙探索', author: 'Emily Brown', copies: '2' },
        { id: '4', title: '健康生活', author: 'Mike Johnson', copies: '5' }
      ]
    };
  },
  methods: {
    addBook() {
      console.log('addBook 被调用'); // 用于调试：检查是否进入函数

      if (!this.newBook.title.trim() || !this.newBook.author.trim()) {
        this.$message.error('请填写完整的书名和作者');
        return;
      }

      const newId = (this.tableData.length + 1).toString();
      this.tableData.push({
        id: newId,
        title: this.newBook.title.trim(),
        author: this.newBook.author.trim(),
        copies: this.newBook.copies.toString()
      });

      // 清空输入框
      this.newBook.ID = '';
      this.newBook.title = '';
      this.newBook.author = '';
      this.newBook.copies = 0;
    },

    deleteBook(index) {
      this.tableData.splice(index, 1);
    }
  }
}
</script>